﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PgBirdie.Core.Model.Database.Structure;

namespace PgBirdie.Core.Model.Database.AccessControl
{
    public class PgPrivilege
    {
        public string Id { get; private set; }
        public PgRole Role { get; private set; }
        public PgDbObject Target { get; private set; }
        public PgPrivilegeCommandType CommandType { get; private set; }
        public IList<PgPrivilegeType> Types { get; private set; }
        public int OrderNo { get; set; }

        public PgPrivilege(PgRole role, object target, PgPrivilegeCommandType commandType, IList<PgPrivilegeType> types)
        {
            Role = role;
            Target = (PgDbObject)target;
            CommandType = commandType;
            Types = types;
            Id = GetId();
        }

        private string GetId()
        {
            var id = new StringBuilder();

            if (Target is PgSchema)
            {
                var schema = (PgSchema) Target;
                id.AppendFormat("{0}", schema.Name);
            }
            else if (Target is PgSequence)
            {
                var sequence = (PgSequence) Target;
                id.AppendFormat("{0}|{1}", sequence.Schema.Name, sequence.Name);
            }
            else if (Target is PgTable)
            {
                var table = (PgTable) Target;
                id.AppendFormat("{0}|{1}", table.Schema.Name, table.Name);
            }

            id.AppendFormat("|{0}", CommandType);
            id.AppendFormat("|{0}", String.Join("|", Types.Select(c => c.ToString()).ToArray()));
            id.AppendFormat("|{0}", Role.Name);

            return id.ToString();
        }
    }
}